package com.grey_zoo.lottery.presenter;

import org.json.JSONException;
import org.json.JSONObject;

import ZhongXinFenPai.TCallback;
import ZhongXinFenPai.TEvent;
import ZhongXinFenPai.TIntent;
import ZhongXinFenPai.TObserver;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.Toast;

import com.grey_zoo.lottery.bean.MyUserInfo;
import com.grey_zoo.lottery.event.TecentEvent;
import com.grey_zoo.lottery.eventhandler.BombEventHandler;
import com.grey_zoo.lottery.global.GlobalValue;
import com.grey_zoo.lottery.listener.BaseUIListener;
import com.grey_zoo.lottery.net.NetUtil;
import com.grey_zoo.lottery.util.ConfigSharePreferenceUtils;
import com.grey_zoo.lottery.util.PromptManager;
import com.grey_zoo.lottery.util.Util;
import com.grey_zoo.lottery.view.manager.MiddleManager;
import com.grey_zoo.lottery.view.manager.TitleManager;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

public class TecentEventManager implements TObserver {
	
	
	public LoginListener listen;
	
	public static TecentEventManager tecent = new TecentEventManager();

	public TecentEventManager() {
		RegisterEvent();

	}

	public void RegisterEvent() {

		TIntent.getInstance().registerEvent(TecentEvent.class, this);

	}

	@Override
	public void onEvent(TEvent event, TCallback callback)
			throws NoSuchMethodException, Exception, Exception {
		// TODO Auto-generated method stub
		TecentEvent tecentevent = (TecentEvent) event;

		switch (tecentevent.flag) {

		case 0:
			//System.out.println("fffffffffffffff");
			CreateInstance();

			break;
		case 1:
			//System.out.println("fffffffffffffff");
			tryLogin(tecentevent.listener);
			
			break;
		case 2:
			 getQQUserInfo(tecentevent.listener);
			break;
		case 3:
			qqLogin();
			break;
		case 4:
			analyzeUserInfo(tecentevent.response);
			break;
		case 5:
			loginout();
			break;
		default:
			break;

		}

	}

	public void CreateInstance() {
		GlobalValue.tencent = Tencent.createInstance(GlobalValue.APP_ID,
				GlobalValue.activity);

	}

	public boolean tryLogin(LoginListener listener) {

		 ConfigSharePreferenceUtils sharePreferenceUtils = new ConfigSharePreferenceUtils(
				GlobalValue.activity);

		if (!NetUtil.checkNet(GlobalValue.activity)) {

			Toast.makeText(GlobalValue.activity, "请检查网络~~", Toast.LENGTH_SHORT)
					.show();

			listener.onFail();

			return false;

		}

		String token = sharePreferenceUtils.getString("token", "");
		String expires = sharePreferenceUtils.getString("expires", "");
		String openId = sharePreferenceUtils.getString("openId", "");

		if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
				&& !TextUtils.isEmpty(openId)) {
			GlobalValue.tencent.setAccessToken(token, expires);
			GlobalValue.tencent.setOpenId(openId);
		}

		
		if (GlobalValue.tencent.isSessionValid()) {
			
			if (getQQUserInfo(listener)) {
				GlobalValue.hasLogin = true;
				
			}
			
			return true;
		} else {
			listener.onFail();
			return false;
		}
	}
	
	
	public static interface LoginListener {

		void onSucceed();

		void onFail();

	}
	
	
	public boolean getQQUserInfo(LoginListener listener) {
		listen=listener;
		ConfigSharePreferenceUtils sharePreferenceUtils = new ConfigSharePreferenceUtils(
				GlobalValue.activity);

		String token = sharePreferenceUtils.getString("token", "");

		if (token.equals("")) {

			return false;
		}
	

		final UserInfo info = new UserInfo(GlobalValue.activity,
				GlobalValue.tencent.getQQToken());
		
		GlobalValue.activity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				info.getUserInfo(new BaseUIListener(GlobalValue.activity,
						"get_simple_userinfo", listen));
			}
		});

		return true;
	}

	
	
	
	
	public void qqLogin() {
		// qq登录
		
		if (!GlobalValue.tencent.isSessionValid()) {
			//PromptManager.closeProgressDialog();
			GlobalValue.tencent.login(GlobalValue.activity, "all",
					new IUiListener() {

						@Override
						public void onError(UiError arg0) {
							// TODO 自动生成的方法存根
							Toast.makeText(GlobalValue.activity, "网络错误，请稍后再试~~",
									Toast.LENGTH_SHORT).show();
						}

						@Override
						public void onComplete(Object arg0) {
							// TODO 自动生成的方法存根

							try {
								JSONObject jsonObject = (JSONObject) arg0;

								String token = jsonObject
										.getString(Constants.PARAM_ACCESS_TOKEN);
								String expires = jsonObject
										.getString(Constants.PARAM_EXPIRES_IN);
								String openId = jsonObject
										.getString(Constants.PARAM_OPEN_ID);

								saveToSp(token, expires, openId);

								if (!TextUtils.isEmpty(token)
										&& !TextUtils.isEmpty(expires)
										&& !TextUtils.isEmpty(openId)) {
									GlobalValue.tencent.setAccessToken(token,
											expires);
									GlobalValue.tencent.setOpenId(openId);
								}

								PromptManager
										.showProgressDialog(GlobalValue.activity);
								getQQUserInfo(new LoginListener() {

									@Override
									public void onSucceed() {
										// TODO 自动生成的方法存根
										// Toast.makeText(MainActivity.this,
										// "登陆成功~~", Toast.LENGTH_SHORT).show();
										// PromptManager.closeProgressDialog();
									//	MiddleManager.getInstance().NoticeAll();
										TitleManager.getInstance()
												.setLoginText(
														GlobalValue.username);
										
										 BombEventHandler.BombCheckMoneyEventHandler(1);
										//GlobalValue.userMoney = checkAndGetBmobMoney();
										MiddleManager.getInstance().NoticeAll();
									//	MainActivity.initSlideMenuFragment();
										PromptManager.closeProgressDialog();

									}

									@Override
									public void onFail() {
										// TODO 自动生成的方法存根
										// Toast.makeText(MainActivity.this,
										// "登陆失败~~,请稍后再试~~",
										// Toast.LENGTH_SHORT).show();
										// PromptManager.closeProgressDialog();
									}
								});

								loginSuccess();

								// MiddleManager.getInstance().pop();

							} catch (JSONException e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
						}

						private void loginSuccess() {
							// TODO 自动生成的方法存根
							GlobalValue.hasLogin = true;
							// 获取用户信息
							MiddleManager.getInstance().pop();

							TitleManager.getInstance().setLoginText(
									GlobalValue.username);

							//GlobalValue.userMoney = checkAndGetBmobMoney();
							BombEventHandler.BombCheckMoneyEventHandler(1);

						}

						private void saveToSp(String token, String expires,
								String openId) {
							// TODO 自动生成的方法存根
							GlobalValue.sharePreferenceUtil.putString("token", token);
							GlobalValue.sharePreferenceUtil.putString("expires", expires);
							GlobalValue.sharePreferenceUtil.putString("openId", openId);
						}

						@Override
						public void onCancel() {
							// TODO 自动生成的方法存根

						}
					});
		} else {
			Toast.makeText(GlobalValue.activity, "已经登录", Toast.LENGTH_SHORT)
					.show();
		}

	}

	
	
	public static void analyzeUserInfo(JSONObject response) {
		// TODO 自动生成的方法存根

		String nickName = "a";
		String imgUrl = "b";
		String openid = null;
		if (GlobalValue.info == null) {

			GlobalValue.info = new MyUserInfo();

		}
		/*
		 * try { nickName=response.getString("nickname");
		 * imgUrl=response.getString("figureurl_qq_2");
		 * 
		 * 
		 * } catch (JSONException e) { // TODO 自动生成的 catch 块
		 * e.printStackTrace(); }
		 */

		/*
		 * if(TextUtils.isEmpty(nickName)||TextUtils.isEmpty(imgUrl)){
		 * 
		 * Toast.makeText(GlobalValue.context, "数据出错~~",
		 * Toast.LENGTH_SHORT).show(); return ;}
		 */

		try {
			nickName = response.getString("nickname");
			imgUrl = response.getString("figureurl_qq_2");
		} catch (JSONException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		// System.out.println("DENGLU6");

		GlobalValue.info.setImgUrl(imgUrl);
		GlobalValue.info.setNickName(nickName);

		System.out.println("1" + nickName + "1");
		// 设置全局的用户名
		GlobalValue.username = nickName;

		// getBitmap();

	}
	
	
	public static void loginout() {
		// TODO 自动生成的方法存根
		GlobalValue.tencent.logout(GlobalValue.activity);
		GlobalValue.hasLogin = false;
		MiddleManager.getInstance().NoticeAll();
	}

	
	public static void getBitmap() {

		if (!NetUtil.checkNet(GlobalValue.activity)) {

			Toast.makeText(GlobalValue.activity, "请检查网络~~", Toast.LENGTH_SHORT)
					.show();

			return;

		}

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO 自动生成的方法存根
				Bitmap bitmap = Util.getbitmap(GlobalValue.info.getImgUrl());
				GlobalValue.info.setImgBitmap(bitmap);
			}
		}).run();
	}

	
	
	
	
	
	
	
	public static TecentEventManager getInstance() {

		return tecent;
	}

	
	
	
}
